import axios from 'axios'
import cefsharpAdapter from '../cefsharp'

// === API 实例创建和配置 ===
const api = axios.create({
    baseURL: process.env.VUE_APP_API_ROOT,
    timeout: 10000,
    responseType: 'json'
})

// === 工具函数 ===
export function shouldUseCefSharp(request) {
    const isCefSharpEndpoint = (
        /\/monitor\/(ports|devices|variables|code-types|hardware)/.test(request.url) ||
        /\/groups/.test(request.url) ||
        /\/settings/.test(request.url) ||
        /\/device/.test(request.url) ||
        /\/download/.test(request.url) ||
        /\/monitor\/lt645\/options/.test(request.url) ||
        /\/edge/.test(request.url) ||
        /\/user/.test(request.url)  // 添加用户相关接口
    )
    return (
        (request.method === 'get' && isCefSharpEndpoint && cefsharpAdapter.checkEnvironment()) ||
        (['post', 'put', 'delete'].includes(request.method) && isCefSharpEndpoint)
    )
}

export function handleSuccessResponse(response) {
    const { url, method } = response.config
    
    // 只针对分组/设备/设置/下载相关的增删改查
    if (
        /\/monitor\/(ports|devices|variables|code-types)/.test(url) ||
        /\/groups/.test(url) ||
        /\/settings/.test(url) ||
        /\/device/.test(url) ||
        /\/download/.test(url) ||
        /\/edge/.test(url)
    ) {
        // 只对增删改查（POST/PUT/DELETE）做处理
        if (['post', 'put', 'delete'].includes(method)) {
            console.log('✅ [API] 已完成增删改查:', url, method)
        }
    }
}

/**
 * 打开文件选择对话框
 * @param {Object} options 对话框选项
 * @param {string} options.title 对话框标题
 * @param {string} options.filter 文件过滤器，格式：'描述 (*.ext)|*.ext|描述 (*.*)|*.*'
 * @param {string} options.defaultExt 默认文件扩展名
 * @returns {Promise<{filePath: string}>} 选择的文件路径
 */
export async function openFileDialog(options) {
    console.log('📁 [API] 打开文件对话框:', options)
    try {
        if (!cefsharpAdapter.checkEnvironment()) {
            throw new Error('CEFSharp环境不可用')
        }
        const response = await cefsharpAdapter.callNativeMethod('OpenFileDialog', JSON.stringify(options))
        console.log('✅ [API] 文件对话框响应成功:', response)
        return response
    } catch (error) {
        console.error('❌ [API] 打开文件对话框失败:', error)
        throw error
    }
}

/**
 * 打开目录选择对话框
 */
export async function openFolderDialog() {
    console.log('📁 [API] 打开目录对话框:')
    try {
        if (!cefsharpAdapter.checkEnvironment()) {
            throw new Error('CEFSharp环境不可用')
        }
        const response = await cefsharpAdapter.callNativeMethod('OpenFolderDialog')
        console.log('✅ [API] 目录对话框响应成功:', response)
        return response
    } catch (error) {
        console.error('❌ [API] 打开目录对话框失败:', error)
        throw error
    }
}

export async function openExternalBrowserLink(param) {
    console.log('📁 [API] 打开注册页面:')
    try {
        if (!cefsharpAdapter.checkEnvironment()) {
            throw new Error('CEFSharp环境不可用')
        }
        const response = await cefsharpAdapter.callNativeMethod('OpenExternalBrowserLink', param)
        console.log('✅ [API] 注册页面响应成功:', response)
        return response
    } catch (error) {
        console.error('❌ [API] 打开注册页面失败:', error)
        throw error
    }
}
export default api 